import sys,os,cgi,time
sys.path.insert(0, os.path.split(sys.path[0])[0])

query = os.getenv("QUERY_STRING",'') 
kwargs = cgi.parse_qs(query)
run_profiler = int(kwargs.get('profile',['0'])[0])

def main():
	import re
	import urllib

	import cnd
	import perf
	import tag

	def iso(d):
		return '-'.join([d[:4],d[4:6],d[6:8]])

	def time_str(t):
		t=min(t,60*60*24-1)
		t=max(t,-60*60*24+1)
		if t<=-60:
			sign='-'
		else:
			sign=''
		return sign+time.strftime("%H:%M",time.gmtime(abs(t)))

	query = os.getenv("QUERY_STRING",'') 
	kwargs = cgi.parse_qs(query)
	date = kwargs.get('date',[time.strftime("%Y%m%d")])[0]
	date_iso = iso(date)
	tags = [t.lower() for t in re.split("\s+",kwargs.get('tags',[''])[0]) if t]
	tidy = kwargs.get('tidy',[''])[0].lower()

	by_type = cnd.by_type(date,tags)

	if False:
		print "HTTP/1.1 200 ok"
		print "Content-Type: text/html"     # HTML is following
		print
		print "<title>%s %s</title>" % (date_iso,"/".join(tags))
		print """<html><head>
		<STYLE>
		<!--
		a {text-decoration:none}
		//-->
		</STYLE>
		</head>"""
	else:
		import head
		head.header()

	print "<body>"
	# date navigation v2
	print '<table border="0" cellspacing="1" cellpadding="5"><tr>'
	dates_per_row=11
	dcnt=0
	for i,d in enumerate(cnd.dates()):
		bt = dict([(k,len(v)) for k,v in cnd.by_type(d,tags).items()])
		if bt['order']==0 or d>time.strftime("%Y%m%d"): color='#EEEEEE'
		elif bt['error']>0: color='#FF0000'
		elif bt['todo']>0: color='#FFFF00'
		else: color='#00FF00'
		if tags:
			tags_url="&tags="+urllib.quote(" ".join(tags))
		else:
			tags_url=""
		if tidy:
			tidy_url="&tidy=%s" % tidy
		else:
			tidy_url=""
		if tidy in ('1','yes','true','on') and bt['order']==0:
			pass
		else:
			print """<th bgcolor=%s><a href="status.py?date=%s%s%s">%s</a><br>%d:%d:%d</th>""" % (color,d,tags_url,tidy_url,iso(d),bt['order'],bt['todo'],bt['error'])
			if dcnt%dates_per_row==dates_per_row-1:
				print "</tr><tr>"
			dcnt += 1
	print "</tr></table>"

	# header
	if tags:
		tags_hdr=" ".join(tags)
	else:
		tags_hdr=""
	# tags
	tags_a = '<a href="tags.py?date=%s">select tag</a>' % date
	print '<h1><a href="status.py?date=%s">%s</a> %s conditions (%s)</h1>' % (date,date_iso,tags_hdr,tags_a)

	# job by status
	if True:
		print '<form name="status" method="GET" action="action.py">'
		print '<input type="text" name="kind">'
		print '<input type="submit" value="add" name="action">'
		print '<input type="submit" value="remove" name="action">'
		print '<br><br>'
		status_list = ['order','todo','active','sleep','error','ignore','ok']
		print '<table border="1" cellpadding="5" cellspacing="0">'
		for s in status_list:
			status_a = '<a href="list.py?date=%s&status=%s">%s</a>' % (date,s,s)
			print "<th>%s (%d)</th>" % (status_a,len(by_type[s]))
		rowcnt = max([len(v) for v in by_type.values()])
		for i in range(rowcnt):
			print "<tr>"
			for s in status_list:
				if i >= len(by_type[s]):
					print "<td>-</td>"
				else:
					j = sorted(by_type[s])[i]
					if cnd.exists(j+'.ok',date): color = '#00FF00'
					elif cnd.exists(j+'.ignore',date): color = '#EEEEEE'
					elif cnd.exists(j+'.error',date): color = '#FF0000'
					elif cnd.exists(j+'.run',date): color = '#FFFF00'
					else: color = '#FFFFFF'
					sel = '<input type="checkbox" name="%s" value="%s">' % (j,date)
					print """<td bgcolor=%s>%s <a href="job.py?date=%s&job=%s">%s</a><br></td>""" % (color,sel,date,j,j)
			print "</tr>"
		print "</table>"
		print "</form>"

	# performance
	if True:
		print '<h1>%s execution times %s</h1>' % (date_iso,tags_hdr)
		print '<table border="1" cellpadding="5" cellspacing="0">'
		print '<tr><th>rank</th><th>jobname</th><th>real time<br>[seconds]</th><th>median<br>real time<br>[seconds]</th><th>real time /<br>median real<br>time</th>'
		print '<th>start time</th><th>median<br>start time</th><th>start time -<br>median<br>start time</th>'
		print '<th>end time</th><th>median<br>end time</th><th>end time -<br>median<br>end time</th></tr>'
		t_sum=0
		mt_sum=0
		for i,(j,t) in enumerate(sorted(perf.jobs_real_times(date,tags).items(),key=lambda x:x[1],reverse=True)):
			mt = perf.med_real_time(j)
			t_factor = 1.0*t/mt
			if t_factor<=0.25:
				color = '#FF00FF'
			elif t_factor<=0.75:
				color = '#00FF00'
			elif t_factor<=1.25:
				color = '#FFFFFF'
			elif t_factor>=2.0:
				color = '#FF0000'
			else:
				color = '#FFFF00'
			tf = 1.0*t/mt
			print '<tr><td>%s</td><td><a href="perf.py?job=%s">%s</a></td><td>%d</td><td>%s</td><td bgcolor=%s>%4.2f</td>' % (i+1,j,j,t,mt,color,tf)
			st = perf.job_start_time(j,date)
			mst = perf.med_start_time(j)
			td=st-mst
			if td<=-60:
				color='#00FF00'
			elif td>=60*60*2:
				color='#FF0000'
			elif td>=60*30:
				color='#FFFF00'
			else:
				color='#FFFFFF'
			print '<td>%s</td><td>%s</td><td bgcolor=%s>%s</td>' % (time_str(st),time_str(mst),color,time_str(td))
			et = perf.job_end_time(j,date)
			met = perf.med_end_time(j)
			td=et-met
			if td<=-60:
				color='#00FF00'
			elif td>=60*60*2:
				color='#FF0000'
			elif td>=60*30:
				color='#FFFF00'
			else:
				color='#FFFFFF'
			print '<td>%s</td><td>%s</td><td bgcolor=%s>%s</td></tr>' % (time_str(et),time_str(met),color,time_str(td))
			t_sum+=t
			mt_sum+=mt
		print '<tr><td>%s</td><td>%s</td><td>%d</td><td>%s</td><td>%4.2f</td>' % ('-','TOTAL',t_sum,mt_sum,1.0*t_sum/max(1,mt_sum))
		print '<td>-</td><td>-</td><td>-</td>'
		print '<td>-</td><td>-</td><td>-</td></tr>'
		print '</table>'

	print "</body></html>"

if run_profiler:
	import profile
	profile.run("main()","rivulet-cgi-status.profile.stats")
else:
	main()
